/**
* @file json_parser_utils.cpp
*
* Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/

#include "common/json_parser_utils.h"
#include "common/log_inner.h"


namespace acl {
    aclError JsonParserUtils::ParseJson(const char_t *const buffer, nlohmann::json &js)
    {
        if (strlen(buffer) == 0UL) {
            ACL_LOG_DEBUG("buffer is empty, no need parse json.");
            return ACL_SUCCESS;
        }
        try {
            js = nlohmann::json::parse(std::string(buffer));
        } catch (const nlohmann::json::exception &e) {
            ACL_LOG_INNER_ERROR("[Check][JsonFile]invalid json buffer, exception:%s.", e.what());
            return ACL_ERROR_INVALID_PARAM;
        }
        ACL_LOG_DEBUG("parse json from buffer successfully.");
        return ACL_SUCCESS;
    }

    aclError JsonParserUtils::GetJsonCtxByKey(const char_t *const buffer,
                                              std::string &strJsonCtx, const std::string &subStrKey, bool &found) {
        found = false;
        nlohmann::json js;
        aclError ret = JsonParserUtils::ParseJson(buffer, js);
        if (ret != ACL_SUCCESS) {
            ACL_LOG_INNER_ERROR("parse json from content failed, ret = %d", ret);
            return ret;
        }
        const auto configIter = js.find(subStrKey);
        if (configIter != js.end()) {
            strJsonCtx = configIter->dump();
            found = true;
        }
        return ACL_SUCCESS;
    }
} // namespace acl